package site.wetsion.galio.sdk.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import site.wetsion.galio.sdk.common.GalioClientDetailsProperties;
import site.wetsion.galio.sdk.common.GalioOauthConstant;
import site.wetsion.galio.sdk.common.UserDetails;

/**
 * 用于校验用户登录，获取用户信息的工具类
 *
 * @author weixin
 * @version 1.0
 * @CLassName UserAuthUtil
 * @date 2019/5/16 11:21 AM
 */
public class UserAuthUtil {

    private final static Logger logger = LoggerFactory.getLogger(UserAuthUtil.class);

    private GalioClientDetailsProperties galioClientDetailsProperties;

    public UserAuthUtil(GalioClientDetailsProperties galioClientDetailsProperties) {
        this.galioClientDetailsProperties = galioClientDetailsProperties;
    }

    /**
     * 尝试登录
     *
     * @Date 11:44 AM 2019/5/16
     * @Param [username, password]
     * @return boolean
     **/
    public boolean tryLogin(String username, String password) {
        JSONObject result = null;
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> params= new LinkedMultiValueMap<>();
        params.add(GalioOauthConstant.USERNAME, username);
        params.add(GalioOauthConstant.PASSWORD, password);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set("clientId", galioClientDetailsProperties.getClientId());
        headers.set("clientSecret", galioClientDetailsProperties.getClientSecret());
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);
        ResponseEntity<String> responseEntity;
        try {
            responseEntity = restTemplate.postForEntity(galioClientDetailsProperties.getUserCheckUrl(), entity, String.class);
            result = JSON.parseObject(responseEntity.getBody());
            if (result.getBooleanValue("success")) {
                return true;
            } else {
                logger.info("用户 {} 登录校验失败, 原因{}", result.getString("message"));
                return false;
            }
        } catch (Exception e) {
            logger.info("用户 {} 登录校验失败: {}", username, e.getMessage());
        }
        return false;
    }

    /**
     * 获取用户信息
     *
     * @Date 11:49 AM 2019/5/16
     * @Param [username]
     * @return site.wetsion.galio.sdk.common.UserDetails
     **/
    public UserDetails userDetails(String username) {
        JSONObject result = null;
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> params= new LinkedMultiValueMap<>();
        params.add(GalioOauthConstant.USERNAME, username);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set("clientId", galioClientDetailsProperties.getClientId());
        headers.set("clientSecret", galioClientDetailsProperties.getClientSecret());
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);
        ResponseEntity<String> responseEntity;
        try {
            responseEntity = restTemplate.postForEntity(
                    galioClientDetailsProperties.getUserDetailsUrl(), entity, String.class);
            result = JSON.parseObject(responseEntity.getBody());
            if (result.getBooleanValue("success")) {
                UserDetails userDetails = new UserDetails();
                JSONObject user = result.getJSONObject("data");
                userDetails.setPassword(user.getString("password"));
                userDetails.setUsername(user.getString("username"));
                return userDetails;
            } else {
                logger.info("用户 {} 登录校验失败, 原因{}", result.getString("message"));
                return null;
            }
        } catch (Exception e) {
            logger.info("用户 {} 登录校验失败: {}", username, e.getMessage());
            return null;
        }
    }
}
